package com.yjt.sousou.main;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.textfield.TextInputEditText;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yjt.sousou.Api;
import com.yjt.sousou.Constant;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseActivity;
import com.yjt.sousou.base.BaseEntity;
import com.yjt.sousou.create.CreateNewOrderActivity;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.integral.RankingActivity;
import com.yjt.sousou.main.entity.MenuBean;
import com.yjt.sousou.main.entity.OrderFilterBean;
import com.yjt.sousou.user.AccountManager;
import com.yjt.sousou.user.LoginActivity;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.HDPreference;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

public class MainActivity extends BaseActivity {
    @BindView(R.id.fl_main)
    FrameLayout mFlMain;
    @BindView(R.id.tab_selector)
    TabLayout mTabLayout;
    @BindView(R.id.vp_content)
    ViewPager mViewPager;
    @BindView(R.id.drawer_content)
    FrameLayout mDrawerContent;
    @BindView(R.id.tv_work_state)
    TextView mTvWorkState;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_department)
    TextView mTvDepartment;
    @BindView(R.id.ll_menu)
    LinearLayout mLlMenu;
    @BindView(R.id.iv_filter)
    TextView mIvFilter;
    @BindView(R.id.iv_top_click)
    ImageView mIvTopClick;

    private PopupWindow mPop;
    private List<OrderFragment> mFragments = new ArrayList<>();
    private String[] mTitles = null;
    int currentIndex;
    private List<MenuBean> mMenuBeans = new ArrayList<>();
    private String permission;
    @Override
    protected Object setContentLayout() {
        return R.layout.activity_main;
    }
    //117  维修员
    //118  部门报修 报单人
    //124  不显示我的报修
    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        permission =  HDPreference.getUserId(LoginTag.PERMISSION.name());
        if(permission.contains("117")){
            mTitles = new String[]{"我的接单","待接单",permission.contains("118")?"我的报修":"报修列表"};
            mTvWorkState.setVisibility(View.VISIBLE);
            mFragments.add(OrderFragment.newInstance(0));
            mFragments.add(OrderFragment.newInstance(1));
            mFragments.add(OrderFragment.newInstance(2));
        }else {
            if(permission.contains("118")&&!permission.contains("124")){
                mTitles = new String[]{"全部报修","我的报修"};
                mFragments.add(OrderFragment.newInstance(2));
                mFragments.add(OrderFragment.newInstance(3));
            }else {
                mTitles = new String[]{"全部报修"};
                mFragments.add(OrderFragment.newInstance(2));
            }
        }
        mUserId =  HDPreference.getUserId(LoginTag.USER_ID.name());
        setText();
        NewsPagerAdapter pagerAdapter = new NewsPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mViewPager.setAdapter(pagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setInlineLabel(true);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }
            @Override
            public void onPageSelected(int i) {
                currentIndex = i;
            }
            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
        getSupportFragmentManager().beginTransaction().add(R.id.drawer_content, OrderFilterFragment.newInstance()).commit();
    }

    private void setText() {
        String userName = HDPreference.getUserId(LoginTag.USER_NAME.name());
        mTvName.setText(userName);
        String workstate = HDPreference.getUserId(LoginTag.WORK_STATE.name());
        mTvWorkState.setText(workstate);
        String department = HDPreference.getUserId(LoginTag.DEPARTMENT.name());
        String duty = HDPreference.getUserId(LoginTag.DUTY.name());
        mTvDepartment.setText(department+" | "+duty);
        if(permission.contains("117")){
            mMenuBeans.add(new MenuBean(0,"在岗状态",R.mipmap.main_menu_work_state,false));
        }
        if(permission.contains("117")|| permission.contains("115")){
            mMenuBeans.add(new MenuBean(1,"绩效排名",R.mipmap.main_menu_ranking,false));
        }
        mMenuBeans.add(new MenuBean(2,"修改密码",R.mipmap.main_menu_password,false));
        mMenuBeans.add(new MenuBean(3,"退出登录",R.mipmap.main_menu_exit,false));
    }

    public int getCurrentIndex(){
        return currentIndex;
    }

    private boolean isFilterClick = false;
    @OnClick({R.id.tv_create_order,R.id.iv_filter,R.id.ll_menu})
    void onClick(View v){
        switch (v.getId()){
            case R.id.tv_create_order:
                Intent intent = new Intent(this, CreateNewOrderActivity.class);
                startActivityForResult(intent, Constant.ORDER_FINISH);
                break;
            case R.id.iv_filter:
                isFilterClick = !isFilterClick;
                if(isFilterClick){
                    mIvFilter.setBackgroundResource(R.mipmap.filter_icon_click);
                }else {
                    mIvFilter.setBackgroundResource(R.mipmap.filter_icon);
                }
                mDrawerContent.setVisibility(mDrawerContent.getVisibility()==View.GONE?View.VISIBLE:View.GONE);
                break;
            case R.id.ll_menu:
                mIvTopClick.setBackgroundResource(R.mipmap.main_arrow_click);
                showMenu();
                break;
                default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Constant.ORDER_FINISH && resultCode == RESULT_OK){
            if(mFragments.size()>1){
                mViewPager.setCurrentItem(2);
            }
            for (OrderFragment fragment : mFragments) {
                fragment.refresh();
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    @Subscribe
    public void handleSomethingElse(OrderFilterBean event) {
        mDrawerContent.setVisibility(View.GONE);
    }

    private void showMenu() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_menu,null);
        RecyclerView recyclerView =  view.findViewById(R.id.lv_menu);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        BaseQuickAdapter adapter = new BaseQuickAdapter<MenuBean,BaseViewHolder>(R.layout.item_menu,mMenuBeans) {
            @Override
            protected void convert(BaseViewHolder helper, MenuBean item) {
                TextView tv = helper.getView(R.id.tv_name);
                tv.setText(item.getName());
                tv.setCompoundDrawablesWithIntrinsicBounds(item.getIconId(),0,0,0);
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mPop.dismiss();
                setMenuClick(mMenuBeans.get(position).getId());
            }
        });
        recyclerView.setAdapter(adapter);
        mPop = new PopupWindow(view, 3 * mScreenWidth / 9,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
                mIvTopClick.setBackgroundResource(R.mipmap.main_arrow_normal);
            }
        });
        int ivWidth = mTvDepartment.getWidth();
        int offset = 3 * mScreenWidth / 9 - ivWidth;
        mPop.showAsDropDown(mLlMenu,-offset,15);
    }

    private void setMenuClick(int position) {
        switch (position){
            case 0:
                showStatePop();
                makeWindowDark();
                break;
            case 1:
                startActivity(RankingActivity.class);
                break;
            case 2:
                changePasswordPop();
                makeWindowDark();
                break;
            case 3:
                exit();
                break;
                default:
        }
    }

    private void exit() {
        OkGo.<Finish>post(Api.get().getExit()).tag(this)
                .params("user_id",mUserId)
                .execute(new DialogCallback<Finish>(Finish.class,this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish finish = response.body();
                        if(finish.getReturncode().equals("0")){
                            showToast("退出成功");
                            startActivity(LoginActivity.class);
                            AccountManager.setSingState(false);
                            finish();
                        }else {
                            showToast("退出失败:"+ finish.getReturnmsg());
                        }
                    }
                });
    }

    //修改密码
    private void changePasswordPop() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_change_password,null);
        ImageView ivClose = view.findViewById(R.id.tv_close);
        TextView tvPopTitle = view.findViewById(R.id.tv_pop_title);
        tvPopTitle.setText("修改密码");
        final TextInputEditText editOldPassword = view.findViewById(R.id.edit_old_password);
        final TextInputEditText editNewPassword = view.findViewById(R.id.edit_new_password);
        final TextInputEditText editConfirmPassword = view.findViewById(R.id.edit_confirm_password);
        TextView btnChange = view.findViewById(R.id.btn_change);
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mFlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = HDPreference.getUserId(LoginTag.USER_NAME.name());
                String old = editOldPassword.getText().toString();
                String newStr = editNewPassword.getText().toString();
                String confirm = editConfirmPassword.getText().toString();
                if(!newStr.equals(confirm)){
                    showToast("两次密码不一致");
                    return;
                }
                OkGo.<BaseEntity>post(Api.get().getChangePassword()).tag(this)
                        .params("username",username)
                        .params("old_password",old)
                        .params("new_password",newStr)
                        .execute(new DialogCallback<BaseEntity>(BaseEntity.class,MainActivity.this) {
                            @Override
                            public void onSuccess(Response<BaseEntity> response) {
                                BaseEntity entity = response.body();
                                if(entity.getReturncode().equals("0")){
                                    showToast("修改成功");
                                    mPop.dismiss();
                                }else {
                                    showToast("修改失败："+entity.getReturnmsg());
                                }
                            }
                        });
            }
        });
    }
    //切换工作状态
    private void showStatePop() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_change_work_state,null);
        TextView tv_in_work = view.findViewById(R.id.tv_in_work);
        TextView tv_out_work = view.findViewById(R.id.tv_out_work);
        TextView tv_pop_title = view.findViewById(R.id.tv_pop_title);
        tv_pop_title.setText("工作状态");
        String stateStr = mTvWorkState.getText().toString();
        if(stateStr.equals("[在岗]")){
            tv_in_work.setBackgroundResource(R.drawable.login_btn_bg);
            tv_in_work.setTextColor(ContextCompat.getColor(this,R.color.white));
            tv_out_work.setBackgroundResource(R.drawable.work_state_out_bg);
            tv_out_work.setTextColor(ContextCompat.getColor(this,R.color.gray_text));
        }else {
            tv_in_work.setBackgroundResource(R.drawable.work_state_out_bg);
            tv_in_work.setTextColor(ContextCompat.getColor(this,R.color.gray_text));
            tv_out_work.setBackgroundResource(R.drawable.login_btn_bg);
            tv_out_work.setTextColor(ContextCompat.getColor(this,R.color.white));
        }
        ImageView ivClose = view.findViewById(R.id.tv_close);
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mFlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_in_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
              changeWorkState(1);
            }
        });
        tv_out_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
                changeWorkState(2);
            }
        });
    }

    private void changeWorkState(final int state){
        OkGo.<Finish>post(Api.get().getChangeState())
                .tag(this)
                .params("opt_uid",mUserId)
                .params("state",state)
                .execute(new DialogCallback<Finish>(Finish.class,this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        String stateStr = state==1?"[在岗]":"[离岗]";
                        HDPreference.setUserId(LoginTag.WORK_STATE.name(),stateStr);
                        mTvWorkState.setText(stateStr);
                    }
                });
    }

    private class NewsPagerAdapter extends FragmentStatePagerAdapter {

        public NewsPagerAdapter(@NonNull FragmentManager fm, int behavior) {
            super(fm, behavior);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }
    }
}
